import { insertNodeCallBack } from '@/handles/common/add-node/helper';
import { useBaseInfoWithOut } from '@/store/modules/base-info';
const useBaseInfo = useBaseInfoWithOut();

var isPackageFlag = false;
var defaultAttitude = '';
function customOperation(obj, resolve) {
    var id = obj.buttonId;
    if (id.lastIndexOf('_') > 0) {
        id = obj.id.substr(0, obj.id.lastIndexOf('_'));
    }

    if (id.indexOf('_') == 0) {
        id = '-' + id.substr(1);
    }
    if (/^(-)?\d+$/.test(id)) {
        // 调用平台分装的ajax方法
        var url =
            _ctxPath + '/rest/worklfowcomponent/permission/operation/' + id + '?option.n_a_s=1';

        jQuery.ajax({
            type: 'GET',
            url: url,
            data: null,
            dataType: 'json',
            beforeSend: CsrfGuard.beforeAjaxSend,
            async: true,
            success: function (result) {
                if ((result != null || result != 'null') && result.data) {
                    result = result.data;

                    // 因为改造后的方法数据结构不一致，先写死，后面改造
                    result.base_submit =
                        '[{"hasProcessChange":false,"hasSubmit":false,"id":"2","isSystem":true,"key":"Comment","label":"permission.operation.Comment","pcClick":"dealDoZcdbFunc","showValue":"暂存待办","specifiesReturnToMe":false,"submitType":"1","type":"2"},{"hasProcessChange":false,"hasSubmit":false,"id":"3","isSystem":true,"key":"ContinueSubmit","label":"permission.operation.ContinueSubmit","pcClick":"submitClickFunc","showValue":"提交","specifiesReturnToMe":false,"submitType":"1","type":"2"},{"color":"#d4642b","hasProcessChange":false,"hasSubmit":false,"icon":"syIcon sy-termination","id":"15","isSystem":true,"key":"Terminate","label":"permission.operation.Terminate","pcClick":"stepStopFunc","showValue":"终止","specifiesReturnToMe":false,"submitType":"1","type":"2"},{"color":"#1f85ec","hasProcessChange":false,"hasSubmit":false,"icon":"syIcon sy-revoke","id":"24","isSystem":true,"key":"Cancel","label":"permission.operation.Cancel","pcClick":"dealCancelFunc","showValue":"撤销","specifiesReturnToMe":false,"submitType":"1","type":"2"},{"color":"#1f85ec","hasProcessChange":false,"hasSubmit":false,"icon":"syIcon sy-transfer","id":"28","isSystem":true,"key":"Transfer","label":"permission.operation.Transfer","pcClick":"transferFunc","showValue":"移交","specifiesReturnToMe":false,"submitType":"1","type":"2"}]';
                    result.base_handel =
                        '[{"hasProcessChange":false,"hasSubmit":false,"id":"1","isSystem":true,"key":"Track","label":"permission.operation.Track","pcClick":"trackBoxFunc","showValue":"跟踪","specifiesReturnToMe":false,"submitType":"0","type":"4"},{"hasProcessChange":false,"hasSubmit":false,"id":"4","isSystem":true,"key":"Archive","label":"permission.operation.Archive","pcClick":"","showValue":"处理后归档","specifiesReturnToMe":false,"submitType":"0","type":"4"},{"hasProcessChange":false,"hasSubmit":false,"id":"5","isSystem":true,"key":"Opinion","label":"permission.operation.Opinion","pcClick":"","showValue":"意见","specifiesReturnToMe":false,"submitType":"0","type":"3"},{"hasProcessChange":false,"hasSubmit":false,"id":"6","isSystem":true,"key":"CommonPhrase","label":"permission.operation.CommonPhrase","pcClick":"","showValue":"常用语","specifiesReturnToMe":false,"submitType":"0","type":"3"},{"hasProcessChange":false,"hasSubmit":false,"id":"7","isSystem":true,"key":"UploadAttachment","label":"permission.operation.UploadAttachment","pcClick":"","showValue":"上传附件","specifiesReturnToMe":false,"submitType":"0","type":"3"},{"hasProcessChange":false,"hasSubmit":false,"id":"8","isSystem":true,"key":"Print","label":"permission.operation.Print","pcClick":"","showValue":"打印","specifiesReturnToMe":false,"submitType":"0","type":"4"},{"hasProcessChange":false,"hasSubmit":false,"id":"9","isSystem":true,"key":"UploadRelDoc","label":"permission.operation.UploadRelDoc","pcClick":"","showValue":"关联文档","specifiesReturnToMe":false,"submitType":"0","type":"3"},{"hasProcessChange":false,"hasSubmit":false,"id":"10","isSystem":true,"key":"EditWorkFlow","label":"permission.operation.EditWorkFlow","pcClick":"","showValue":"编辑流程","specifiesReturnToMe":false,"submitType":"0","type":"4"},{"hasProcessChange":false,"hasSubmit":false,"id":"11","isSystem":true,"key":"Pigeonhole","label":"permission.operation.Pigeonhole","pcClick":"","showValue":"归档","specifiesReturnToMe":false,"submitType":"0","type":"4"},{"hasProcessChange":false,"hasSubmit":false,"id":"12","isSystem":true,"key":"RepeatSend","label":"permission.operation.RepeatSend","pcClick":"","showValue":"重复发起","specifiesReturnToMe":false,"submitType":"0","type":"4"},{"hasProcessChange":false,"hasSubmit":false,"id":"13","isSystem":true,"key":"ReMove","label":"permission.operation.ReMove","pcClick":"","showValue":"删除","specifiesReturnToMe":false,"submitType":"0","type":"4"},{"hasProcessChange":false,"hasSubmit":false,"id":"14","isSystem":true,"key":"AppTile","label":"permission.operation.AppTile","pcClick":"","showValue":"应用磁贴","specifiesReturnToMe":false,"submitType":"0","type":"1"},{"color":"#1f85ec","hasProcessChange":false,"hasSubmit":false,"icon":"syIcon sy-notification","id":"16","isSystem":true,"key":"Infom","label":"permission.operation.Infom","pcClick":"addInformFunc","showValue":"知会","specifiesReturnToMe":false,"submitType":"0","type":"0"},{"color":"#1f85ec","hasProcessChange":false,"hasSubmit":false,"icon":"syIcon sy-signature","id":"17","isSystem":true,"key":"AddNode","label":"permission.operation.AddNode","pcClick":"addNode","showValue":"加签","specifiesReturnToMe":false,"submitType":"0","type":"0"},{"color":"#1f85ec","hasProcessChange":false,"hasSubmit":false,"icon":"syIcon sy-current_countersigned","id":"18","isSystem":true,"key":"JointSign","label":"permission.operation.JointSign","pcClick":"currentAssign","showValue":"当前会签","specifiesReturnToMe":false,"submitType":"0","type":"0"},{"color":"#1f85ec","hasProcessChange":false,"hasSubmit":false,"icon":"syIcon sy-signafalse","id":"19","isSystem":true,"key":"RemoveNode","label":"permission.operation.RemoveNode","pcClick":"deleteNodeFunc","showValue":"减签","specifiesReturnToMe":false,"submitType":"0","type":"0"},{"color":"#1f85ec","hasProcessChange":false,"hasSubmit":false,"icon":"syIcon sy-apply-meeting","id":"20","isSystem":true,"key":"moreSign","label":"permission.operation.moreSign","pcClick":"addMoreNode","showValue":"多级会签","specifiesReturnToMe":false,"submitType":"0","type":"0"},{"color":"#1f85ec","hasProcessChange":false,"hasSubmit":false,"icon":"syIcon sy-forwarding","id":"21","isSystem":true,"key":"Forward","label":"permission.operation.Forward","pcClick":"dealForwardFunc","showValue":"转发","specifiesReturnToMe":false,"submitType":"0","type":"1"},{"color":"#1f85ec","hasProcessChange":false,"hasSubmit":false,"icon":"syIcon sy-modify_text","id":"22","isSystem":true,"key":"Edit","label":"permission.operation.Edit","pcClick":"editContentFunc","showValue":"修改正文","specifiesReturnToMe":false,"submitType":"0","type":"4"},{"color":"#1f85ec","hasProcessChange":false,"hasSubmit":false,"icon":"syIcon sy-signa","id":"23","isSystem":true,"key":"Sign","label":"permission.operation.Sign","pcClick":"openSignature","showValue":"签章","specifiesReturnToMe":false,"submitType":"0","type":"4"},{"color":"#1f85ec","hasProcessChange":false,"hasSubmit":false,"icon":"syIcon sy-setting","id":"25","isSystem":true,"key":"SuperviseSet","label":"permission.operation.SuperviseSet","pcClick":"superviseSetFunc","showValue":"督办设置","specifiesReturnToMe":false,"submitType":"0","type":"4"},{"color":"#1f85ec","hasProcessChange":false,"hasSubmit":false,"icon":"syIcon sy-modify_attachment","id":"26","isSystem":true,"key":"allowUpdateAttachment","label":"permission.operation.allowUpdateAttachment","pcClick":"modifyAttFunc","showValue":"修改附件","specifiesReturnToMe":false,"submitType":"0","type":"4"},{"color":"#1f85ec","hasProcessChange":false,"hasSubmit":false,"icon":"syIcon sy-forward_event","id":"27","isSystem":true,"key":"Transform","label":"permission.operation.Transform","pcClick":"transformFunc","showValue":"转事件","specifiesReturnToMe":false,"submitType":"0","type":"1"}]';

                    isPackageFlag = false;
                    var specialNodePolicyMsg = checkSpecialNodePolicy(result);
                    if (specialNodePolicyMsg) {
                        $.alert(specialNodePolicyMsg);
                        return;
                    }

                    var jsonObject = JSON.parse(result.content);
                    // if((nodeattitudeListSize == "0" || nodeattitudeListSize == "") && jsonObject.attitudeAction != ""){
                    //     //如果节点没有态度-但是封装操作有态度那么传入封装的态度
                    //     document.getElementById("hidAttitude").value = jsonObject.attitudeShowName;
                    //     document.getElementById("hidAttitudeCode").value = jsonObject.attitudeAction;
                    //     // $("#hidAttitude").val()
                    // }
                    if (
                        !(
                            jsonObject.attitudeAction == '' ||
                            nodeattitudeListSize == '0' ||
                            nodeattitudeListSize == ''
                        )
                    ) {
                        // defaultAttitude = jsonObject.attitudeAction;
                        isPackageFlag = true;
                    }
                    //如果态度为空 或者没有态度权限，那么直接跳过态度 --如果是回退操作也不出现态度
                    if (
                        !(
                            jsonObject.attitudeAction == '' ||
                            nodeattitudeListSize == '0' ||
                            nodeattitudeListSize == ''
                        ) &&
                        jsonObject.submitAction != 'Return'
                    ) {
                        var attitudeId = null;
                        var showFlagAttitude = false;
                        var showEqAttitude = false;
                        var attitudeJson = new Array();
                        var radioes = document.getElementsByName('attitude');
                        for (var i = 0; i < radioes.length; i++) {
                            var nowAtt = radioes[i];
                            if (nowAtt.checked) {
                                attitudeId = nowAtt;
                            }
                            var valueAtt = nowAtt.getAttribute('value');
                            var type = 0;
                            if (valueAtt !== '' && valueAtt.indexOf('collaboration') > -1) {
                                type = 1;
                            }
                            attitudeJson.push({
                                code: nowAtt.getAttribute('code'),
                                value: nowAtt.getAttribute('value'),
                                type: type,
                            });
                        }
                        if (attitudeId) {
                            if (jsonObject.attitudeAction != attitudeId.getAttribute('code')) {
                                showFlagAttitude = true;
                            }
                            //默认值不想等
                            if (attitudeId.getAttribute('value') != jsonObject.attitudeShowName) {
                                if (
                                    jsonObject.attitudeAction != '' &&
                                    attitudeId.getAttribute('value') != jsonObject.attitudeShowName
                                ) {
                                    showFlagAttitude = true;
                                    var type = 0;
                                    if (
                                        jsonObject.attitudeAction != '' &&
                                        jsonObject.attitudeShowName.indexOf('collaboration') > -1
                                    ) {
                                        type = 1;
                                    }
                                    var addFlag = false;
                                    for (var kk = 0; kk < attitudeJson.length; kk++) {
                                        if (
                                            attitudeJson[kk].code == jsonObject.attitudeAction &&
                                            attitudeId.getAttribute('code') ==
                                                attitudeJson[kk].code &&
                                            (jsonObject.attitudeShowName ==
                                                $.i18n(attitudeJson[kk].value) ||
                                                jsonObject.attitudeShowName ==
                                                    attitudeJson[kk].value)
                                        ) {
                                            defaultAttitude = attitudeJson[kk].code;
                                            showEqAttitude = true;
                                        }
                                        if (
                                            defaultAttitude == $.i18n(attitudeJson[kk].code) ||
                                            defaultAttitude == attitudeJson[kk].code
                                        ) {
                                            defaultAttitude = attitudeJson[kk].code;
                                        }
                                        if (
                                            attitudeJson[kk].code == jsonObject.attitudeAction &&
                                            jsonObject.attitudeShowName !=
                                                $.i18n(attitudeJson[kk].value) &&
                                            jsonObject.attitudeShowName != attitudeJson[kk].value
                                        ) {
                                            addFlag = true;
                                            break;
                                        }
                                    }
                                    if (addFlag) {
                                        //并且把他生成到状态中
                                        //type:是否是国际化显示值   isAction:节点封装的态度
                                        attitudeJson.push({
                                            code: jsonObject.attitudeAction,
                                            value: jsonObject.attitudeShowName,
                                            type: type,
                                            isAction: 'true',
                                        });
                                    }
                                }
                            }
                            attitudeJSONArr = attitudeJson;
                            /**
                             * 是否弹出态度确认框
                             * 1. 封装的态度和选择的态度不一致 弹出态度确认框
                             * 2. 态度一致，操作是回退、撤销、终止时 态度是不同意 不弹出态度确认框
                             * 3. 态度一致，操作不是回退、撤销、终止时 态度是不同意 (提交配置不同意策略 弹出不同意策略的选择，未配置时直接提交)
                             * 4. 态度一致，操作是回退、撤销、终止 态度是非不同意 弹出态度确认框
                             * 5. 态度一致，操作不是回退、撤销、终止 态度时非不同意 不弹出态度确认框
                             */
                            var isReturnTerminateAndCancel =
                                jsonObject.submitAction == 'Return' ||
                                jsonObject.submitAction == 'Terminate' ||
                                jsonObject.submitAction == 'Cancel';
                            if (attitudeId.getAttribute('value') == jsonObject.attitudeShowName) {
                                if (jsonObject.submitAction == 'ContinueSubmit') {
                                    showFlagAttitude = false;
                                } else if (
                                    isReturnTerminateAndCancel &&
                                    attitudeId.getAttribute('code') == 'disagree'
                                ) {
                                    //操作是回退、撤销、终止时 态度是不同意 不弹出态度确认框
                                    showFlagAttitude = false;
                                } else if (
                                    !isReturnTerminateAndCancel &&
                                    attitudeId.getAttribute('code') == 'disagree'
                                ) {
                                    //操作不是回退、撤销、终止时 态度是不同意 弹出态度确认框
                                    showFlagAttitude = true;
                                } else if (
                                    isReturnTerminateAndCancel &&
                                    attitudeId.getAttribute('code') != 'disagree'
                                ) {
                                    //操作是回退、撤销、终止 态度是非不同意 弹出态度确认框
                                    showFlagAttitude = true;
                                } else if (
                                    !isReturnTerminateAndCancel &&
                                    attitudeId.getAttribute('code') != 'disagree'
                                ) {
                                    //操作不是回退、撤销、终止 态度时非不同意 不弹出态度确认框
                                    showFlagAttitude = false;
                                }
                            }
                            defaultProcessAction = jsonObject.submitAction;
                            var defalutBottomHtml = '';
                            if (defaultProcessAction == 'Cancel') {
                                defalutBottomHtml =
                                    '<label  class="margin_t_5 hand" style="display: inline-block;width: 190px;text-align: left;position: relative;top: -7px;">' +
                                    $.i18n('collaboration.workflow.trace.hadToRunBack') +
                                    '</label>';
                            }

                            if (showFlagAttitude) {
                                //如果是提交类型
                                if (
                                    jsonObject.submitAction != '' &&
                                    jsonObject.processAction == ''
                                ) {
                                    showAttitude(defalutBottomHtml, result, true);
                                } else {
                                    showAttitude(defalutBottomHtml, result, false);
                                }
                            } else {
                                //不验证态度直接触发
                                handleAndSubmit(result, resolve);
                            }
                        } else {
                            //不验证态度直接触发
                            handleAndSubmit(result, resolve);
                        }
                        isPackageFlag = true;
                    } else {
                        if (defaultAttitude == '' || defaultAttitude == null) {
                            defaultAttitude = $('input[name="attitude"]:checked').attr('code');
                        }
                        //    attitudeJSONArr = getAttitudeJSonArr(jsonObject);
                        //不验证态度直接触发
                        handleAndSubmit(result, resolve);
                    }
                }
            },
        });
    }
}

function addNode(param, resolve) {
    var appName = 'collaboration';
    // if (validateProcess()) {
    //     return
    // }

    let { template, summary, affair, currentUser, workflow, other } =
        useBaseInfo.baseInfo.businessData;
    const { secretLevel } = useBaseInfo.baseInfo;
    var isForm = template && template.bodyType == '20';
    var insertNodeParams = {};
    insertNodeParams.workitemId = '';
    insertNodeParams.processId = workflow.processId || workflow.processTemplateId;
    insertNodeParams.nodeId = 'start';
    insertNodeParams.currentUserId = currentUser.id;
    insertNodeParams.performer = affair.memberId;
    insertNodeParams.caseId = '';
    insertNodeParams.appName = affair.appEnumStr || other.moduleTypeName;
    insertNodeParams.isForm = isForm;
    insertNodeParams.accountId = currentUser.loginAccount;
    insertNodeParams.callback = insertNodeCallBack;
    insertNodeParams.summaryId = summary.id;
    insertNodeParams.affairId = affair.id;
    insertNodeParams.isTemplete = template && template.isTemplate;
    insertNodeParams.useNowexpirationTime = 'true';
    insertNodeParams.SPK = 'default';
    insertNodeParams.formRecordId = affair.formRecordId;
    insertNodeParams.needValidateOnBeforeAdd = 'false';
    insertNodeParams.needAddNodeDiagram = 'true';
    insertNodeParams.changeNodeMessage = {};
    insertNodeParams.accessFileSecretLevel = secretLevel?.value || '';
    var NPS = 'default';
    if (isForm) {
        NPS = 'form';
    }
    insertNodeParams.NPS = NPS;

    //changeNodeMessage
    //手动加一下这几个参数--------
    param.changeNodeMessage.NPS = 'default';
    param.changeNodeMessage.currentUserId = currentUser.id;
    param.changeNodeMessage.currentUserName = currentUser.name;

    //--------------------------------

    insertNodeParams.needAddNodeDiagram = 'false';
    insertNodeParams.changeNodeMessage.NPS = 'default';
    insertNodeParams.changeNodeMessage.appName = affair.appEnumStr || other.moduleTypeName;
    insertNodeParams.changeNodeMessage.currentUserId = currentUser.id;
    insertNodeParams.changeNodeMessage.currentUserName = currentUser.name;
    insertNodeParams.changeNodeMessage = param.changeNodeMessage;

    var processXml = document.querySelector('#process_xml');
    if (!processXml) {
        processXml = document.createElement('input');
        processXml.type = 'hidden';
        processXml.id = 'process_xml';
        document.body.appendChild(processXml);
    }

    var readyObjectJSON = document.querySelector('#readyObjectJSON');
    if (!readyObjectJSON) {
        readyObjectJSON = document.createElement('input');
        readyObjectJSON.type = 'hidden';
        readyObjectJSON.id = 'readyObjectJSON';
        document.body.appendChild(readyObjectJSON);
    }
    insertNode(insertNodeParams, resolve);
    resolve();
}

function handleAndSubmit(result, resolve) {
    var jsonObject = JSON.parse(result.content);

    if (jsonObject.submitAction != 'Return') {
        var params = {};
        params.isOperationDesignerModel = true;
        params.changeNodeMessage = jsonObject.processActionDetail; //然后判断操作的
        params.changeNodeMessage.processAction = jsonObject.processAction;

        // if (jsonObject.processAction != "") {
        //   //如果操作后有提交那么回调方法就不在刷新流程图直接提交了
        //   if (jsonObject.submitAction != "") {
        //     //流程改变+提交操作需要记录流程图的信息，方便回滚
        //     pushPageWorkflowInfo();

        //     params.callback = function () {
        //       var subParam = {};
        //       subParam.changeNodeMessage = params.changeNodeMessage;
        //       subParam.isOperationDesignerModel = params.isOperationDesignerModel;
        //       blurButtonClick(JSON.parse(result.base_submit), jsonObject.submitAction, subParam);
        //     };
        //   }

        //   __preSubmitFormContent(function () {
        //     blurButtonClick(JSON.parse(result.base_handel), jsonObject.processAction, params);
        //   });
        // } //如果只有提交操作那么直接派发

        // if (jsonObject.processAction == "" && jsonObject.submitAction != "") {
        //   blurButtonClick(JSON.parse(result.base_submit), jsonObject.submitAction, params);
        // }

        console.log([
            '提交并加签',
            JSON.parse(result.base_submit),
            jsonObject.submitAction,
            params,
        ]);
        addNode(params, resolve);
    } else {
        var params = {};
        params.changeNodeMessage = true; //回退 - 回退上节点

        if (jsonObject.returnDetailData === 'Return') {
            stepBackCallBack();
        } else {
            var returnArr = jsonObject.returnDetailData.split('|');
            params.showReGo = true;
            params.showToMe = true;

            if (returnArr[1] == '0') {
                params.showToMe = 'false';
            } else if (returnArr[1] == '1') {
                params.showReGo = 'false';
            }

            if ('SpecifiesReturn' === returnArr[0]) {
                //回退到指定人
                specifiesReturnFunc(params);
            } else if ('SpecifiesReturnCreate' === returnArr[0]) {
                //回退到发起人
                params.stepBackToNodeId = 'start';
                specifiesReturnFunc(params);
            }
        }
        resolve();
    }
}

function checkSpecialNodePolicy(result) {
    let { template, summary, affair, currentUser, workflow } = useBaseInfo.baseInfo.businessData;
    var msg = '';
    var tempIsTemplate = !(
        !template ||
        !template.id ||
        template.id == '' ||
        template.id == '0' ||
        template.id == '-1'
    );
    var isForm = template && template.bodyType == '20';

    if (tempIsTemplate && isForm) {
        return msg;
    }

    var jsonObject = JSON.parse(result.content);
    var specialNodePolicy = new Array();

    if (tempIsTemplate) {
        specialNodePolicy = ['formaudit', 'vouch'];
    } else {
        specialNodePolicy = ['formaudit', 'vouch', 'newsaudit', 'bulletionaudit'];
    } //然后判断操作

    if (jsonObject.submitAction != 'Return' && jsonObject.processAction != '') {
        var changeNodeMessage = jsonObject.processActionDetail;

        if (changeNodeMessage && changeNodeMessage.policyId) {
            var policy = changeNodeMessage.policyId;
            var policyArray = [];

            if (policy && jsonObject.processAction != 'moreSign') {
                policyArray.push(policy);
            } else if (policy) {
                policyArray = policy;
            }

            var colTypeName = $.i18n('common.free.coll.label');

            if (tempIsTemplate) {
                colTypeName = $.i18n('common.collaboration.template.label');
            }

            for (var i = 0; i < policyArray.length; i++) {
                if ($.inArray(policyArray[i], specialNodePolicy) >= 0) {
                    msg = $.i18n(
                        'collaboration.canNotDeal.specialNodePolicy.js',
                        $.i18n('node.policy.' + policyArray[i]),
                        colTypeName
                    );
                    break;
                }
            }
        }
    }

    return msg;
}

export default (item) =>
    new Promise((resolve) => {
        customOperation(item, resolve);
    });
